//
//  HBInvestCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/11/30.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBInvestCtrl.h"
#import "HBProductProtocolCtrl.h"
#import "CheckValid.h"
#import "HBInvestSureCtrl.h"
#import "HBIdentifierCheckCtrl.h"
#import "HBGetUserStatusManager.h"
#import "HBAddBankCtrl.h"

#import "HBUserInvestParam.h"
#import "HBUserInvestParser.h"
#import "HBUserInvestInfo.h"
#import "HBInvestManager.h"
#import "HBMyBankAccountCtrl.h"

#import "HBUserInvestInfo.h"
#import "HBUserInvestParam.h"
#import "HBUserInvestParser.h"

#define leftMargan  (IsIphone4?15:(IsIphone5?15:(IsIphone6?15:15))) 
#define leftMargan1 (IsIphone4?113:(IsIphone5?113:(IsIphone6?113:113)))

@interface HBInvestCtrl ()
<UITextFieldDelegate>

@property (nonatomic, strong) UILabel *desLable;
@property (nonatomic, strong) UILabel *moneyLable;
@property (nonatomic, strong) UITextField *moneyTF;
@property (nonatomic, strong) UILabel *dayIncomeLable;
@property (nonatomic, strong) UIButton *productProtocolBtn;
@property (nonatomic, strong) UIButton *submitBtn;
@property (nonatomic, strong) UILabel *msgLable;
@property (nonatomic) float totalRate;

@end

//立即买入界面
@implementation HBInvestCtrl

#pragma mark -
#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
}

/*
- (void)buildLayout
{
    [super buildLayout];
    self.title = @"立即买入";
    self.view.backgroundColor = [LCCommon getColor:@"f4f5f6"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
   
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToEndEdit)];
    [self.view addGestureRecognizer:tapG];
    
//    UIView *topLine =
    [self createSepratorLineWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"fecf91"] superView:self.view];
//    UIView *topBG =
    [self createSepratorLineWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30) backgroundColor:[LCCommon getColor:@"fff9df"] superView:self.view];
    self.desLable = [self createLableWithText:@"年化收益8%起" font:[UIFont systemFontOfSize:12.0f] color:[LCCommon getColor:@"cd7500"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 0, SCREEN_WIDTH-2*(leftMargan), 30) superView:self.view];

//    UIView *midBG =
    [self createSepratorLineWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, 44) backgroundColor:[LCCommon getColor:@"ffffff"] superView:self.view];
    //    UIView *midLine =
    [self createSepratorLineWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"dfdfdf"] superView:self.view];
    self.moneyLable = [self createLableWithText:@"金额(元)" font:[UIFont systemFontOfSize:16.0f] color:[LCCommon getColor:@"333333"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 30, 95, 44) superView:self.view];
    self.moneyTF = [self createTFWithPlaceHolder:@"最低买入金额100元" placeHolderColor:[LCCommon getColor:@"cbcbcb"] font:[UIFont systemFontOfSize:14] color:[LCCommon getColor:@"333333"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan1, 30, SCREEN_WIDTH-(leftMargan + leftMargan1), 44) superView:self.view];
    self.moneyTF.keyboardType = UIKeyboardTypeNumberPad;
    UIView *buttomLine = [self createSepratorLineWithFrame:CGRectMake(0, 74, SCREEN_WIDTH, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"dfdfdf"] superView:self.view];
    self.dayIncomeLable = [self createLableWithText:@"今日增加收益0.00元" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"333333"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 74, 200, 40) superView:self.view];
    
    self.productProtocolBtn = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH-(leftMargan)-150, 74, 150, 40) normalBackgroundColor:[UIColor clearColor] disabledBackgroundColor:[UIColor clearColor]  higlightedBackgroundColor:[UIColor clearColor] normalFontColor:[LCCommon getColor:@"2281f7"] higlightedFontColor:[LCCommon getColor:@"2281f7"] disabledFontColor:[LCCommon getColor:@"2281f7"] title:@"查看产品协议" contentHorizontalAlignment:UIControlContentHorizontalAlignmentRight font:[UIFont systemFontOfSize:14] superView:self.view];
    self.productProtocolBtn.enabled = YES;
    
    self.msgLable = [self createLableWithText:@"" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"fc353b"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, self.dayIncomeLable.y+self.dayIncomeLable.height, SCREEN_WIDTH-2*(leftMargan), 15) superView:self.view];
    self.msgLable.hidden = NO;
    
    self.submitBtn = [self createButtonWithFrame:CGRectMake(leftMargan, buttomLine.y+80, SCREEN_WIDTH-2*(leftMargan), 44) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"f24545"] higlightedBackgroundColor:[LCCommon getColor:@"f24545"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"ff9797"] title:@"立即投资" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.view];
    [self reloadViewType];
    
}
 */

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"立即投资";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToEndEdit)];
    [self.view addGestureRecognizer:tapG];
    
    //    UIView *topLine =
    [self createSepratorLineWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"fecf91"] superView:self.view];
    //    UIView *topBG =
    [self createSepratorLineWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30) backgroundColor:[LCCommon getColor:@"323232"] superView:self.view];
    self.desLable = [self createLableWithText:@"年化收益8%起" font:[UIFont systemFontOfSize:12.0f] color:[LCCommon getColor:@"919191"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 0, SCREEN_WIDTH-2*(leftMargan), 30) superView:self.view];
    
    //    UIView *midBG =
    [self createSepratorLineWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 44) backgroundColor:[UIColor clearColor] superView:self.view];
    //    UIView *midLine =
    [self createSepratorLineWithFrame:CGRectMake(leftMargan, 50, SCREEN_WIDTH-2*(leftMargan), 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"585858"] superView:self.view];
    self.moneyLable = [self createLableWithText:@"金额(元)" font:[UIFont systemFontOfSize:16.0f] color:[LCCommon getColor:@"b1b1b1"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 50, 95, 44) superView:self.view];
    self.moneyTF = [self createTFWithPlaceHolder:@"最低买入金额100元" placeHolderColor:[LCCommon getColor:@"585858"] font:[UIFont systemFontOfSize:14] color:[LCCommon getColor:@"ffffff"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan1, 50, SCREEN_WIDTH-(leftMargan + leftMargan1), 44) superView:self.view];
    self.moneyTF.keyboardType = UIKeyboardTypeNumberPad;
//    self.moneyTF.secureTextEntry = YES;
    UIView *buttomLine = [self createSepratorLineWithFrame:CGRectMake(leftMargan, 94, SCREEN_WIDTH-2*leftMargan, 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"585858"] superView:self.view];
    self.dayIncomeLable = [self createLableWithText:@"今日增加收益0.00元" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"777777"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, 94, 200, 40) superView:self.view];
    
    
    self.msgLable = [self createLableWithText:@"" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"fc353b"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, self.dayIncomeLable.y+self.dayIncomeLable.height, SCREEN_WIDTH-2*(leftMargan), 15) superView:self.view];
    self.msgLable.hidden = NO;
    
    self.submitBtn = [self createButtonWithFrame:CGRectMake(leftMargan, buttomLine.y+80, SCREEN_WIDTH-2*(leftMargan), 44) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"bd3737"] higlightedBackgroundColor:[LCCommon getColor:@"d43333"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"fd7a7a"] title:@"立即投资" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.view];
    [self reloadViewType];
    
    self.productProtocolBtn = [self createButtonWithFrame:CGRectMake((leftMargan), self.submitBtn.y+self.submitBtn.height+5, SCREEN_WIDTH-15, 40) normalBackgroundColor:[UIColor clearColor] disabledBackgroundColor:[UIColor clearColor]  higlightedBackgroundColor:[UIColor clearColor] normalFontColor:[LCCommon getColor:@"777777"] higlightedFontColor:[LCCommon getColor:@"777777"] disabledFontColor:[LCCommon getColor:@"777777"] title:@" 已同意《服务计划协议》《借款合同》《债权转让协议》" contentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft font:[UIFont systemFontOfSize:12] superView:self.view];
    [self.productProtocolBtn setImage:[UIImage imageNamed:@"invest_select"] forState:UIControlStateNormal];
    self.productProtocolBtn.enabled = YES;
    if (isIphone4or5)
    {
        [self.productProtocolBtn.titleLabel setFont:[UIFont systemFontOfSize:11]];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    float interestRate = (int)([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.interestRate floatValue]*10000)/100.0;
    float increaseRate = (int)([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.increaseRate floatValue]*10000)/100.0;
    float totalRate = interestRate + increaseRate;
    self.totalRate = totalRate;
    if ([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.bindCardStatus integerValue])
    {
        self.desLable.text = [HBInvestManager sharedHBInvestManager].userInvestLimitInfo.investLimitInfo;
    }
    else
    {
        self.desLable.text = [NSString stringWithFormat:@"年化收益%.2f%%起",totalRate];
    }
  
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)doBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark - private

- (NSString *)getCurrentDayIncomeWithCurrentMoney:(NSString *)money
{
    return [NSString stringWithFormat:@"%.2lf",([money doubleValue]*self.totalRate/100.0)/365];
}

- (void)reloadViewType
{
    if (self.dayIncomeLable.text.length>0)
    {
        NSRange range = [self.dayIncomeLable.text rangeOfString:@"今日增加收益"];
        if (range.location != NSNotFound)
        {
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:self.dayIncomeLable.text];
            [attr addAttribute:NSForegroundColorAttributeName value:[LCCommon getColor:@"fc353b"] range:NSMakeRange(range.location+range.length, self.dayIncomeLable.text.length-7)];
            self.dayIncomeLable.attributedText = attr;
            
        }
    }
    
    
    
}



- (UIScrollView *)createScrollViewWithFrame:(CGRect)frame contentSize:(CGSize)contentSize andSuperView:(UIView *)superView
{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:frame];
    scrollView.contentSize = contentSize;
    scrollView.bounces = NO;
    [superView addSubview:scrollView];
    return scrollView;
}

- (UITextField *)createTFWithPlaceHolder:(NSString *)placeHolder placeHolderColor:(UIColor *)placeColor font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UITextField *textField = [[UITextField alloc]initWithFrame:frame];
    textField.backgroundColor = [UIColor clearColor];
    textField.placeholder = placeHolder;
    textField.font = font;
    textField.textColor = fontColor;
    textField.textAlignment = textAlignment;
    textField.delegate = self;
    [textField setValue:placeColor forKeyPath:@"_placeholderLabel.textColor"];
    [superView addSubview:textField];
    return textField;
}

- (UILabel *)createLableWithText:(NSString *)text font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UILabel *lable = [[UILabel alloc]initWithFrame:frame];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = text;
    lable.font = font;
    lable.textColor = fontColor;
    lable.textAlignment = textAlignment;
    [superView addSubview:lable];
    return lable;
}

- (UIView *)createSepratorLineWithFrame:(CGRect)frame backgroundColor:(UIColor *)bgColor superView:(UIView *)superView
{
    UIView *sepratorLine = [[UIView alloc]initWithFrame:frame];
    sepratorLine.backgroundColor = bgColor;
    [superView addSubview:sepratorLine];
    return sepratorLine;
}

- (UIButton *)createButtonWithFrame:(CGRect)frame normalBackgroundColor:(UIColor *)normalBGColor disabledBackgroundColor:(UIColor *)disabledBGColor higlightedBackgroundColor:(UIColor *)higlightedBGColor  normalFontColor:(UIColor *)normalFontColor higlightedFontColor:(UIColor *)higlightedFontColor disabledFontColor:(UIColor *)disabledFontColor title:(NSString *)title contentHorizontalAlignment:(UIControlContentHorizontalAlignment)textAlignment font:(UIFont *)font superView:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundColor:normalBGColor];
    [button setBackgroundColor:normalBGColor forState:UIControlStateNormal];
    [button setBackgroundColor:disabledBGColor forState:UIControlStateDisabled];
    [button setBackgroundColor:higlightedBGColor forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalFontColor forState:UIControlStateNormal];
    [button setTitleColor:disabledFontColor forState:UIControlStateDisabled];
    [button setTitleColor:higlightedFontColor forState:UIControlStateHighlighted];
    button.titleLabel.font = font;
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:textAlignment];
    [superView addSubview:button];
    button.enabled = NO;
    [button.layer setCornerRadius:4.0f];
    button.layer.masksToBounds = YES;
    return button;
}


#pragma mark -
#pragma mark - active


- (void)clickToEndEdit
{
    [self.moneyTF resignFirstResponder];

}

- (void)clickButton:(UIButton *)sender
{
    if (sender == self.productProtocolBtn)
    {
        HBProductProtocolCtrl *productProtocolCtrl  = [[HBProductProtocolCtrl alloc]init];
        [self.navigationController pushViewController:productProtocolCtrl animated:YES];
    }
    else if (sender == self.submitBtn)
    {
        if ([CheckValid checkStrIsEmpty:self.moneyTF.text])
        {
            [self.moneyTF becomeFirstResponder];
            self.msgLable.hidden = NO;
            self.msgLable.text = @"买入金额不能为空";
            
        }
        else if (![CheckValid isLegalCharacter:self.moneyTF.text])
        {
            self.msgLable.hidden = NO;
            self.msgLable.text = @"买入金额不得包含特殊字符";
            [self.moneyTF becomeFirstResponder];
        }
        else if([self.moneyTF.text integerValue]/100<1)
        {
            //
            self.msgLable.hidden = NO;
            self.msgLable.text = @"买入金额不得少于100元";
            [self.moneyTF becomeFirstResponder];
        }
        else if([self.moneyTF.text doubleValue]>[[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.singleTimeLimit doubleValue])
        {
            self.msgLable.hidden = NO;
            self.msgLable.text = @"买入金额不得超出单笔限额";
            [self.moneyTF becomeFirstResponder];
        }
        else
        {
            [self clickToEndEdit];
            [self requestToInvest];
        }
        
    }
}


#pragma mark -
#pragma mark - delegate


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //    [self showTFClearBtnWithTextField:textField];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

#pragma mark -
#pragma mark - notify

-(void)textDidChange{
    
    self.msgLable.text = @"";
    
    if (self.moneyTF.text.length > 0 ) {
        self.submitBtn.enabled = YES;
        
        self.dayIncomeLable.text = [NSString stringWithFormat:@"今日增加收益%@元",[self getCurrentDayIncomeWithCurrentMoney:self.moneyTF.text]];
        [self reloadViewType];
    }else{
        self.submitBtn.enabled = NO;
        
    }
}

#pragma mark -
#pragma mark - request

- (void)requestToInvest
{
    //下面这些将来替换为新的接口
    
    /*
    if ([HBGetUserStatusManager sharedHBGetUserStatusManager].isAllAuthor)
    {
        HBInvestSureCtrl *identifierCheckCtrl = [[HBInvestSureCtrl alloc]init];
        [self.navigationController pushViewController:identifierCheckCtrl animated:YES];
    }
    else
    {
        [CustomLoadingView showHudToView:nil];
        [HBGetUserStatusManager requestToGetUserStatusWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
            [CustomLoadingView hideHudForView:nil];
            if ([HBGetUserStatusManager sharedHBGetUserStatusManager].isAllAuthor)
            {
                HBInvestSureCtrl *investCtrl = [[HBInvestSureCtrl alloc]init];
                [self.navigationController pushViewController:investCtrl animated:YES];
            }
            else
            {
                HBAddBankCtrl *checkCtrl = [[HBAddBankCtrl alloc]init];
                checkCtrl.viewpageJumpingFrom = isFromInvestView;
                checkCtrl.isRealName = [[HBGetUserStatusManager sharedHBGetUserStatusManager].userStatusInfo.identityStatus integerValue];
                [self.navigationController pushViewController:checkCtrl animated:YES];
            }
            
        }];
    }
     */
    

    self.msgLable.text = @"";
    [CustomLoadingView showHudToView:self.view];
    HBUserInvestParam *param = [[HBUserInvestParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.investMoney = self.moneyTF.text;
    HBUserInvestParser *parser = [[HBUserInvestParser alloc]init];
    [NetCenter postDataFromURL:Method_userInvest params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code==0)
        {
            HBUserInvestInfo *userInvestInfo = (HBUserInvestInfo *)myResult.result;
            if (![userInvestInfo.bindCardStatus integerValue])
            {
                //未绑卡
                HBAddBankCtrl *checkCtrl = [[HBAddBankCtrl alloc]init];
                checkCtrl.viewpageJumpingFrom = isFromInvestView;
                checkCtrl.isRealName = [userInvestInfo.identityStatus integerValue];
                checkCtrl.investMoney = self.moneyTF.text;
                checkCtrl.userInvestInfo = userInvestInfo;
                [self.navigationController pushViewController:checkCtrl animated:YES];
            }
            else
            {
                [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 60] forKey:INVESTSURE_CODE_TIME];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                HBInvestSureCtrl *investCtrl = [[HBInvestSureCtrl alloc]init];
                investCtrl.userInvestInfo = userInvestInfo;
                investCtrl.investMoney = self.moneyTF.text;
                [self.navigationController pushViewController:investCtrl animated:YES];
            }
          
        }
        else
        {
            self.msgLable.hidden = NO;
            self.msgLable.text = myResult.message;
        }
        [CustomLoadingView hideHudForView:self.view];
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        self.msgLable.text = [error description];
    }];
    
    
}



@end
